//
//  QuestionnaireSurveyViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/19.
//  问卷调查

import UIKit
import YYText

class QuestionnaireSurveyViewController: UIViewController {
    
    /// 106:幸福感问卷       107:生活方式问卷
    var code = 106
    /// 保存选择的index
    private var selectIndexArr = [Int]()
    /// 保存答案
    private var answerArr = [String]()
    private var dataArr = [QuestionnaireListModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

      
        
        addUI()
        getData()
    }
    
    private func getData() {
        var url = ""
        if code == 106 {
            url = "/Check/happy"
        } else if code == 107 {
            url = "/Check/life"
        }
        QINetworkManager.requestJson(urlStr: url, method: .get, parameters: [:]) { json in
            print(json)
            self.dataArr = json.arrayObject?.kj.modelArray(QuestionnaireListModel.self) ?? [QuestionnaireListModel]()
            for _ in 0..<self.dataArr.count {
                self.selectIndexArr.append(-1)
                self.answerArr.append("")
            }
            self.tableView.reloadData()
        }
        
    }

    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFB2B5").cgColor, ColorWithStr("#FCDFE0").cgColor, ColorWithStr("#FFFBFB").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        let explainL = YYLabel().then({
            $0.frame = CGRect(x: 15, y: NAV_HEIGHT, width: SCREEN_WIDTH - 30, height: 70)
            $0.backgroundColor = .white
            $0.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            $0.text = "使用说明：能够实时的收集和分析数据，针对性的解决问题，而不是依赖经验或者过时的数据。"
            $0.numberOfLines = 0
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 15)
            $0.addRoundedCorners(withRadius: 10)
        })
        view.addSubview(explainL)
        
        view.addSubview(tableView)
        
        let submitBtn = UIButton().then {
            $0.frame = CGRect(x: 20, y: SCREEN_HEIGHT - FOOT_HEIGHT - 50, width: SCREEN_WIDTH - 40, height: 40)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("提交", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(submitBtnClick), for: .touchUpInside)
        }
        view.addSubview(submitBtn)
    }
    
    @objc private func submitBtnClick() {
//        for i in selectIndexArr {
//            if i < 0 {
//                ShowHUD(str: "请完善选项")
//                return
//            }
//        }
        var url = ""
        if code == 106 {
            url = "/Check/happyFill"
        } else if code == 107 {
            url = "/Check/lifeFill"
        }
        let str = answerArr.joined(separator: ",")
        QINetworkManager.requestJson(urlStr: url, parameters: ["ids": str]) { json in
            print(json)
            ShowHUD(str: "提交成功")
            self.navigationController?.popViewController(animated: true)
            
            Defaults[\.isLogin] = true
            let window = UIApplication.shared.keyWindow
            window?.switchRootCtrl()
        } fail: { json in
            let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
            if model.code == 106 || model.code == 107 {   //幸福感问卷调查
               let ctl = QuestionnaireSurveyViewController()
               ctl.code = model.code
               self.navigationController?.pushViewController(ctl, animated: true)
           }
        }
        

    }
    

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.frame = CGRect(x: 0, y: NAV_HEIGHT + 80, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - FOOT_HEIGHT - 140)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()


}

extension QuestionnaireSurveyViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        dataArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let model = dataArr[section]
        let size = model.name.tt_size(with: SYSFONTBOLD(ofSize: 14), constrainedToWidth: SCREEN_WIDTH - 40)
        return size.height + 10
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        let model = dataArr[section]
        
        let size = model.name.tt_size(with: SYSFONTBOLD(ofSize: 14), constrainedToWidth: SCREEN_WIDTH - 40)
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 20, y: 5, width: size.width, height: size.height)
            $0.text = model.name
            $0.numberOfLines = 0
            $0.textColor = MainColor
            $0.font = SYSFONTBOLD(ofSize: 14)
        })
        headerView.addSubview(titleL)
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        20
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = dataArr[section]
        return model.children.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        30
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = AnswerListViewCell11()
        cell.selectionStyle = .none
        cell.backgroundColor = .clear
        if selectIndexArr[indexPath.section] == indexPath.row {
            cell.isSelect = true
        }
        let model = dataArr[indexPath.section]
        cell.model = model.children[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectIndexArr[indexPath.section] = indexPath.row
        print(selectIndexArr)
        tableView.reloadData()
        
        let model = dataArr[indexPath.section]
        let childModel = model.children[indexPath.row]
        answerArr[indexPath.section] = childModel.id
    }
    
}


class AnswerListViewCell11: UITableViewCell {
    
    private var selectImgView = UIImageView()
    private var contentL = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addUI()
    }
    func addUI() {
        
        selectImgView = UIImageView().then {
            $0.frame = CGRect(x: 20, y: 0, width: 14, height: 14)
            $0.centerY = self.centerY
            $0.image = UIImage(named: "题_未选择")
        }
        self.addSubview(selectImgView)
        
        contentL = UILabel().then({
            $0.frame = CGRect(x: selectImgView.right + 5, y: 0, width: SCREEN_WIDTH - 50, height: self.height)
            $0.text = "内容内容内容内容内容"
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 13)
        })
        self.addSubview(contentL)
        
    }
    
    var model = AnswerModel() {
        didSet {
            contentL.text = model.name
        }
    }
    
    var isSelect = false {
        didSet {
            if isSelect {
                selectImgView.image = UIImage(named: "题_选择")
            } else {
                selectImgView.image = UIImage(named: "题_未选择")
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

